package moore.ui.handler;

import moore.generator.vhdlGenerator;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

public class VhdlAsmGenerator extends AbstractHandler implements IHandler {

	public Object execute(ExecutionEvent event) throws ExecutionException {
		ISelection selection = HandlerUtil.getCurrentSelection(event);
		if (selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection) selection;
			Object firstElement = structuredSelection.getFirstElement();
			if (firstElement instanceof IFile) {
				IFile model = (IFile) firstElement;
				// create a model URI for the selected resource
				URI modelURI = URI.createPlatformResourceURI(model
						.getFullPath().toString(), true);
				IProject project = model.getProject();
				// create an output folder for the serialized xmi-model
				IFolder srcGenFolder = project.getFolder("vhdl-model");
				if (!srcGenFolder.exists()) {
					try {
						srcGenFolder.create(true, true,
								new NullProgressMonitor());
					} catch (CoreException e) {
						return null;
					}
				}
				this.generateVhdl(modelURI,srcGenFolder);
			}
		}
		return null;
	}
	
	private void generateVhdl(URI modelURI, IFolder srcGenFolder){
		//carico la risorsa
		ResourceSet asmResourceSet=new ResourceSetImpl();
		Resource model=asmResourceSet.getResource(modelURI, true);
		EcoreUtil.resolveAll(asmResourceSet);
		//la logica di generazione eseguita con xtend
		vhdlGenerator.getInstance().generate(model,srcGenFolder);
	}

	public boolean isEnabled() {
		return true;
	}

}
